import axios from 'axios'
import React from 'react'
import {Toast} from 'antd-mobile'
import {refreshTkReq,} from "../apis/goApis";
import LoadingIcon from '../res/images/web/shared/loading-icon.png'
import constants, {test} from "./constants";
import LocalStorageService from "./LocalStorageService";
import {searchParams} from "../containers/mall/mall";


// 配置请求 请求 和 响应拦截器
// request logger for debug
// axios.interceptors.request.use(
//     config => {
//         console.log(`request to ${config.url}`)
//         const {data} = config
//         if (data) {
//             for (let [k, v] of Object.entries(data)) {
//                 console.log(`with data[${k}]: ${v}`)
//             }
//         }
//         return config
//     }
// )

// axios.interceptors.request.use(config => {
//     const url = config.url
//     if (url.includes('/apis/') || url.includes('/lav/')) {
//         const storage = LocalStorageService
//         const isLogin = storage.get('isLogin')
//         if (isLogin) {
//             return config
//         } else {
//             return
//         }
//         // return config
//     } else {
//         return config
//     }
//
// })

// 带 token 请求拦截
// axios.interceptors.request.use(
//     (config) => {
//         const login = LocalStorageService.get('isLogin')
//         console.log(`这个请求${login? '登录了' : '未登录'}`)
//         return config
//     }
// )


axios.interceptors.request.use(
    config => {

        config.withCredentials = false
        // config.timeout = 6000
        let token = localStorage.getItem('access_token')
        const {url} = config
        // const whiteList = [
        //     prefix + '/try/go/newsheadline',
        //     prefix + '/try/go/getstarranklist',
        //     prefix + '/try/go/rtoken',
        //     prefix + '/try/go/newslist',
        //     prefix + '/try/go/newsdetail',
        //     prefix + '/try/go/gamelist',
        //     prefix + '/try/go/reg',
        //     prefix + '/try/go/login',
        //     prefix + '/try/go/livelist',
        //     prefix + '/try/go/gameproxy',
        //     prefix + '/houtai/addgamevideo',
        // ]
        //
        // const i = whiteList.findIndex(whiteUrl => {
        //     return whiteUrl === url
        // })
        //
        // const isInWhiteList = whiteList.findIndex(whiteUrl => whiteUrl === url) > -1
        const isTryGo = url.includes('try/go')
        const isHoutai = url.includes('houtai')

        if (isTryGo || isHoutai) {
            return config
        }


        if (url.includes('oauth2')) {
            return config
        }

        const login = LocalStorageService.get('isLogin')

        if (token && login === true) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        const params = window.location.search
            .slice(1)
            .split('&')
            .map(keyValue => {
                return keyValue.split('=')
            })
            .reduce((acc, cur) => {
                acc[cur[0]] = cur[1]
                return acc
            }, {})
        if (params.webview === 'true' && params.token) {
            config.headers['Authorization'] = `Bearer ${params.token}`
        }
        return config
    }, error => {
        return Promise.reject(error)
    })

const isWebview = searchParams().webview === 'true'

// 刷新请求
axios.interceptors.response.use(res => {
    return res
}, async error => {
    const {response, config} = error
    if (response === undefined) {
        if (error.config.url.includes('app/apis')) {
            if (!isWebview) {
                LocalStorageService.clear()
                window.location = test ? 'http://123.207.85.242:8080/game' : 'http://www.youtoball.com:8080/game'
            }
        }
        return Promise.reject(error)
    }
    if (response.status === 401) {
        // 未授权 请求刷新 token
        const uid = localStorage.getItem('userid')
        const rtk = localStorage.getItem('refresh_token')
        if (rtk === 'undefined') {
            return Promise.reject(error)
        } else {
            const rTkResp = await refreshTkReq({uid, refresh_token: rtk,})
            if (rTkResp.data.err) {
                // 刷新失败
                if (!isWebview) {
                    LocalStorageService.clear()
                    window.location = test ? 'http://123.207.85.242:8080/game' : 'http://www.youtoball.com:8080/game'
                }
                return Promise.reject(error)
            } else {
                // 如果刷新成功
                // 先保存token pairs 到 localStorage
                const {access_token, refresh_token} = rTkResp.data
                localStorage.setItem('access_token', access_token)
                localStorage.setItem('refresh_token', refresh_token)
                // 重新配置失败请求的 config 头部字段
                config.headers['Authorization'] = `Bearer ${access_token}`
                return axios(config)
            }
        }
    } else {
        // 请求有其他失败
        return Promise.reject(error)
    }
})



function checkStatus(response) {
    const errorCode = {
        'other': "未知请求错误",
        '401': "未授权访问",
        '404': "错误的url",
        '500': "服务器内部错误",
        '502': "服务器无响应",
        '504': "服务器响应超时",
        'ECONNABORTED': "客户端连接超时",
    }

    if (response.status) {
        if ((response.status >= 200 && response.status < 300)
            || response.status === 304
            || response.status === 401) {
            return response
        }
        // 4xx-5xx
        // if(response.status>=400 || response.status<600){
        return {
            data: {
                status: response.status,
                code: 303,
                message: errorCode[response.status] || errorCode.other,
            }
        }
    } else {
        return {
            data: {
                status: response.code,
                code: 303,
                message: errorCode[response.code] || errorCode.other,
            }
        }
    }
}

function checkStatusList(responseList) {
    let result = []
    for (let i = 0; i < responseList.length; i++) {
        let resp = responseList[i]
        let respAfterCheck = checkStatus(resp)
        result.push(respAfterCheck)
    }
    return result
}

const LoadingImg = () => <div>
    <img src={LoadingIcon} alt=''/>
    <p>加载中...</p>
</div>

export const callApiRequest = async (endpoint, {verb = 'get', params = {}} = {}) => {
    try {
        Toast.info(LoadingImg())
        const resp = await axios[verb](endpoint, params)
        Toast.hide()
        return checkStatus(resp)
    } catch (e) {
        Toast.hide()
        // 服务器异常(有response)和xhr其他异常(客户端异常等,没有response)
        return checkStatus(e.response || e)
    }
}

export const callApiRequestNotToast = async (endpoint, {verb = 'get', params = {}} = {}) => {
    try {
        const resp = await axios[verb](endpoint, params)
        return checkStatus(resp)
    } catch (e) {
        return checkStatus(e.response || e)
    }
}
export const batchCallApiRequest = async (reqList) => {
    try {
        Toast.info(LoadingImg())
        const responseList = await axios.all(reqList)
        Toast.hide()
        return checkStatusList(responseList)
    } catch (e) {
        Toast.hide()
        return checkStatus(e.response || e)
    }
}
